#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import json
import os
import time
from datetime import datetime, timedelta
from typing import List, Dict, Optional

class Equipment:
    def __init__(self, equipment_id: str, name: str, category: str, model: str, lab_id: str, 
                 purchase_date: str = "", price: float = 0.0, status: str = "可用"):
        self.equipment_id = equipment_id
        self.name = name
        self.category = category
        self.model = model
        self.lab_id = lab_id
        self.purchase_date = purchase_date
        self.price = price
        self.status = status
        self.create_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    
    def to_dict(self) -> dict:
        return {
            'equipment_id': self.equipment_id,
            'name': self.name,
            'category': self.category,
            'model': self.model,
            'lab_id': self.lab_id,
            'purchase_date': self.purchase_date,
            'price': self.price,
            'status': self.status,
            'create_time': self.create_time
        }
    
    @classmethod
    def from_dict(cls, data: dict):
        equipment = cls(
            data['equipment_id'],
            data['name'],
            data['category'],
            data['model'],
            data['lab_id'],
            data.get('purchase_date', ''),
            data.get('price', 0.0),
            data.get('status', '可用')
        )
        equipment.create_time = data.get('create_time', datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
        return equipment
    
    def __str__(self) -> str:
        return f"设备ID：{self.equipment_id} | 名称：{self.name} | 型号：{self.model} | 状态：{self.status}"

class Laboratory:
    def __init__(self, lab_id: str, name: str, location: str, manager: str, capacity: int, description: str = ""):
        self.lab_id = lab_id
        self.name = name
        self.location = location
        self.manager = manager
        self.capacity = capacity
        self.description = description
        self.create_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    
    def to_dict(self) -> dict:
        return {
            'lab_id': self.lab_id,
            'name': self.name,
            'location': self.location,
            'manager': self.manager,
            'capacity': self.capacity,
            'description': self.description,
            'create_time': self.create_time
        }
    
    @classmethod
    def from_dict(cls, data: dict):
        lab = cls(
            data['lab_id'],
            data['name'],
            data['location'],
            data['manager'],
            data.get('capacity', 0),
            data.get('description', '')
        )
        lab.create_time = data.get('create_time', datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
        return lab
    
    def __str__(self) -> str:
        return f"实验室ID：{self.lab_id} | 名称：{self.name} | 位置：{self.location} | 管理员：{self.manager}"

class BorrowRecord:
    def __init__(self, record_id: str, equipment_id: str, borrower: str, borrow_date: str, 
                 expected_return: str, actual_return: str = "", purpose: str = "", remarks: str = ""):
        self.record_id = record_id
        self.equipment_id = equipment_id
        self.borrower = borrower
        self.borrow_date = borrow_date
        self.expected_return = expected_return
        self.actual_return = actual_return
        self.purpose = purpose
        self.remarks = remarks
        self.status = "借用中" if not actual_return else "已归还"
        self.create_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    
    def to_dict(self) -> dict:
        return {
            'record_id': self.record_id,
            'equipment_id': self.equipment_id,
            'borrower': self.borrower,
            'borrow_date': self.borrow_date,
            'expected_return': self.expected_return,
            'actual_return': self.actual_return,
            'purpose': self.purpose,
            'remarks': self.remarks,
            'status': self.status,
            'create_time': self.create_time
        }
    
    @classmethod
    def from_dict(cls, data: dict):
        record = cls(
            data['record_id'],
            data['equipment_id'],
            data['borrower'],
            data['borrow_date'],
            data['expected_return'],
            data.get('actual_return', ''),
            data.get('purpose', ''),
            data.get('remarks', '')
        )
        record.status = data.get('status', '借用中')
        record.create_time = data.get('create_time', datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
        return record
    
    def __str__(self) -> str:
        return f"记录ID：{self.record_id} | 设备ID：{self.equipment_id} | 借用人：{self.borrower} | 状态：{self.status}"

class LabEquipmentSystem:
    
    def __init__(self):
        self.equipments: Dict[str, Equipment] = {}
        self.laboratories: Dict[str, Laboratory] = {}
        self.borrow_records: Dict[str, BorrowRecord] = {}
        self.data_file = "lab_equipment_data.txt"
        self.load_data()
    
    def save_data(self):
        try:
            data = {
                'equipments': {eid: equipment.to_dict() for eid, equipment in self.equipments.items()},
                'laboratories': {lid: lab.to_dict() for lid, lab in self.laboratories.items()},
                'borrow_records': {rid: record.to_dict() for rid, record in self.borrow_records.items()}
            }
            with open(self.data_file, 'w', encoding='utf-8') as f:
                json.dump(data, f, ensure_ascii=False, indent=2)
            print("数据保存成功！")
        except Exception as e:
            print(f"数据保存失败：{e}")
    
    def load_data(self):
        try:
            if os.path.exists(self.data_file):
                with open(self.data_file, 'r', encoding='utf-8') as f:
                    data = json.load(f)
                
                if 'equipments' in data:
                    for eid, equipment_data in data['equipments'].items():
                        self.equipments[eid] = Equipment.from_dict(equipment_data)
                
                if 'laboratories' in data:
                    for lid, lab_data in data['laboratories'].items():
                        self.laboratories[lid] = Laboratory.from_dict(lab_data)
                
                if 'borrow_records' in data:
                    for rid, record_data in data['borrow_records'].items():
                        self.borrow_records[rid] = BorrowRecord.from_dict(record_data)
                
                print("数据加载成功！")
        except Exception as e:
            print(f"数据加载失败：{e}")
    
    def add_equipment(self):
        print("\n=== 添加设备 ===")
        equipment_id = input("请输入设备ID：").strip()
        
        if equipment_id in self.equipments:
            print("该设备ID已存在！")
            return
        
        name = input("请输入设备名称：").strip()
        category = input("请输入设备类别：").strip()
        model = input("请输入设备型号：").strip()
        lab_id = input("请输入所属实验室ID：").strip()
        
        if lab_id and lab_id not in self.laboratories:
            print("实验室ID不存在！请先添加实验室。")
            return
        
        purchase_date = input("请输入购买日期（YYYY-MM-DD，可选）：").strip()
        price_input = input("请输入设备价格（可选）：").strip()
        
        try:
            price = float(price_input) if price_input else 0.0
        except ValueError:
            price = 0.0
        
        if not all([equipment_id, name, category, model]):
            print("设备ID、名称、类别、型号不能为空！")
            return
        
        equipment = Equipment(equipment_id, name, category, model, lab_id, purchase_date, price)
        self.equipments[equipment_id] = equipment
        print(f"设备 {name} 添加成功！")
        self.save_data()
    
    def delete_equipment(self):
        print("\n=== 删除设备 ===")
        equipment_id = input("请输入要删除的设备ID：").strip()
        
        if equipment_id not in self.equipments:
            print("设备ID不存在！")
            return
        
        equipment = self.equipments[equipment_id]
        
        active_borrows = [r for r in self.borrow_records.values() 
                         if r.equipment_id == equipment_id and r.status == "借用中"]
        if active_borrows:
            print("该设备仍有借用记录未归还，无法删除！")
            return
        
        confirm = input(f"确认删除设备 {equipment.name}（{equipment_id}）？(y/n)：").strip().lower()
        
        if confirm == 'y':
            to_delete = [rid for rid, record in self.borrow_records.items() if record.equipment_id == equipment_id]
            for rid in to_delete:
                del self.borrow_records[rid]
            
            del self.equipments[equipment_id]
            print(f"设备 {equipment.name} 删除成功！")
            self.save_data()
        else:
            print("取消删除。")
    
    def update_equipment(self):
        print("\n=== 修改设备信息 ===")
        equipment_id = input("请输入要修改的设备ID：").strip()
        
        if equipment_id not in self.equipments:
            print("设备ID不存在！")
            return
        
        equipment = self.equipments[equipment_id]
        print(f"当前设备信息：{equipment}")
        
        print("\n请输入新信息（直接回车保持原值）：")
        name = input(f"设备名称（{equipment.name}）：").strip()
        category = input(f"设备类别（{equipment.category}）：").strip()
        model = input(f"设备型号（{equipment.model}）：").strip()
        lab_id = input(f"所属实验室ID（{equipment.lab_id}）：").strip()
        purchase_date = input(f"购买日期（{equipment.purchase_date}）：").strip()
        price_input = input(f"设备价格（{equipment.price}）：").strip()
        
        print("设备状态：")
        print("1. 可用")
        print("2. 借用中")
        print("3. 维修中")
        print("4. 已报废")
        status_choice = input(f"状态（当前：{equipment.status}）：").strip()
        status_map = {'1': '可用', '2': '借用中', '3': '维修中', '4': '已报废'}
        status = status_map.get(status_choice, equipment.status)
        
        if lab_id and lab_id not in self.laboratories and lab_id != equipment.lab_id:
            print("实验室ID不存在！")
            return
        
        if name:
            equipment.name = name
        if category:
            equipment.category = category
        if model:
            equipment.model = model
        if lab_id:
            equipment.lab_id = lab_id
        if purchase_date or purchase_date == "":
            equipment.purchase_date = purchase_date
        if price_input:
            try:
                equipment.price = float(price_input)
            except ValueError:
                print("价格必须为数字！")
        if status_choice:
            equipment.status = status
        
        print("设备信息修改成功！")
        self.save_data()
    
    def search_equipment(self):
        print("\n=== 查询设备 ===")
        print("1. 按设备ID查询")
        print("2. 按设备名称查询")
        print("3. 按设备类别查询")
        print("4. 按实验室查询")
        print("5. 按状态查询")
        
        choice = input("请选择查询方式：").strip()
        
        if choice == '1':
            equipment_id = input("请输入设备ID：").strip()
            if equipment_id in self.equipments:
                print(f"\n查询结果：")
                self._display_equipment_detail(self.equipments[equipment_id])
            else:
                print("未找到该设备ID。")
        
        elif choice == '2':
            name = input("请输入设备名称：").strip()
            results = [eq for eq in self.equipments.values() if name in eq.name]
            self._display_equipment_results(results, "名称")
        
        elif choice == '3':
            category = input("请输入设备类别：").strip()
            results = [eq for eq in self.equipments.values() if category in eq.category]
            self._display_equipment_results(results, "类别")
        
        elif choice == '4':
            lab_id = input("请输入实验室ID：").strip()
            results = [eq for eq in self.equipments.values() if eq.lab_id == lab_id]
            self._display_equipment_results(results, "实验室")
        
        elif choice == '5':
            print("请选择设备状态：")
            print("1. 可用")
            print("2. 借用中")
            print("3. 维修中")
            print("4. 已报废")
            status_choice = input("请选择状态：").strip()
            status_map = {'1': '可用', '2': '借用中', '3': '维修中', '4': '已报废'}
            status = status_map.get(status_choice)
            
            if status:
                results = [eq for eq in self.equipments.values() if eq.status == status]
                self._display_equipment_results(results, f"状态（{status}）")
            else:
                print("无效的状态选择！")
        
        else:
            print("无效的选择！")
    
    def _display_equipment_detail(self, equipment: Equipment):
        lab_name = ""
        if equipment.lab_id and equipment.lab_id in self.laboratories:
            lab_name = self.laboratories[equipment.lab_id].name
        
        print(f"设备ID：{equipment.equipment_id}")
        print(f"设备名称：{equipment.name}")
        print(f"设备类别：{equipment.category}")
        print(f"设备型号：{equipment.model}")
        print(f"所属实验室：{lab_name}（{equipment.lab_id}）")
        print(f"购买日期：{equipment.purchase_date}")
        print(f"设备价格：{equipment.price}")
        print(f"设备状态：{equipment.status}")
        print(f"创建时间：{equipment.create_time}")
    
    def _display_equipment_results(self, results: List[Equipment], search_type: str):
        if results:
            print(f"\n按{search_type}查询结果（共{len(results)}条）：")
            for i, equipment in enumerate(results, 1):
                print(f"{i}. {equipment}")
        else:
            print(f"未找到匹配的设备。")
    
    def list_all_equipments(self):
        print("\n=== 所有设备列表 ===")
        if not self.equipments:
            print("暂无设备数据。")
            return
        
        print(f"共有 {len(self.equipments)} 台设备：")
        for i, equipment in enumerate(self.equipments.values(), 1):
            print(f"{i}. {equipment}")
    
    def add_laboratory(self):
        print("\n=== 添加实验室 ===")
        lab_id = input("请输入实验室ID：").strip()
        
        if lab_id in self.laboratories:
            print("该实验室ID已存在！")
            return
        
        name = input("请输入实验室名称：").strip()
        location = input("请输入实验室位置：").strip()
        manager = input("请输入管理员：").strip()
        capacity_input = input("请输入容量：").strip()
        description = input("请输入描述（可选）：").strip()
        
        try:
            capacity = int(capacity_input) if capacity_input else 0
        except ValueError:
            capacity = 0
        
        if not all([lab_id, name, location, manager]):
            print("实验室ID、名称、位置、管理员不能为空！")
            return
        
        laboratory = Laboratory(lab_id, name, location, manager, capacity, description)
        self.laboratories[lab_id] = laboratory
        print(f"实验室 {name} 添加成功！")
        self.save_data()
    
    def delete_laboratory(self):
        print("\n=== 删除实验室 ===")
        lab_id = input("请输入要删除的实验室ID：").strip()
        
        if lab_id not in self.laboratories:
            print("实验室ID不存在！")
            return
        
        equipments_in_lab = [eq for eq in self.equipments.values() if eq.lab_id == lab_id]
        if equipments_in_lab:
            print(f"该实验室仍有 {len(equipments_in_lab)} 台设备，无法删除！")
            return
        
        laboratory = self.laboratories[lab_id]
        confirm = input(f"确认删除实验室 {laboratory.name}（{lab_id}）？(y/n)：").strip().lower()
        
        if confirm == 'y':
            del self.laboratories[lab_id]
            print(f"实验室 {laboratory.name} 删除成功！")
            self.save_data()
        else:
            print("取消删除。")
    
    def update_laboratory(self):
        print("\n=== 修改实验室信息 ===")
        lab_id = input("请输入要修改的实验室ID：").strip()
        
        if lab_id not in self.laboratories:
            print("实验室ID不存在！")
            return
        
        laboratory = self.laboratories[lab_id]
        print(f"当前实验室信息：{laboratory}")
        
        print("\n请输入新信息（直接回车保持原值）：")
        name = input(f"实验室名称（{laboratory.name}）：").strip()
        location = input(f"实验室位置（{laboratory.location}）：").strip()
        manager = input(f"管理员（{laboratory.manager}）：").strip()
        capacity_input = input(f"容量（{laboratory.capacity}）：").strip()
        description = input(f"描述（{laboratory.description}）：").strip()
        
        if name:
            laboratory.name = name
        if location:
            laboratory.location = location
        if manager:
            laboratory.manager = manager
        if capacity_input:
            try:
                laboratory.capacity = int(capacity_input)
            except ValueError:
                print("容量必须为数字！")
        if description or description == "":
            laboratory.description = description
        
        print("实验室信息修改成功！")
        self.save_data()
    
    def list_all_laboratories(self):
        print("\n=== 所有实验室列表 ===")
        if not self.laboratories:
            print("暂无实验室数据。")
            return
        
        print(f"共有 {len(self.laboratories)} 个实验室：")
        for i, lab in enumerate(self.laboratories.values(), 1):
            equipment_count = len([eq for eq in self.equipments.values() if eq.lab_id == lab.lab_id])
            print(f"{i}. {lab} | 设备数量：{equipment_count}")
    
    def borrow_equipment(self):
        print("\n=== 设备借用 ===")
        equipment_id = input("请输入要借用的设备ID：").strip()
        
        if equipment_id not in self.equipments:
            print("设备ID不存在！")
            return
        
        equipment = self.equipments[equipment_id]
        if equipment.status != "可用":
            print(f"设备状态为 {equipment.status}，无法借用！")
            return
        
        record_id = input("请输入借用记录ID：").strip()
        if record_id in self.borrow_records:
            print("该记录ID已存在！")
            return
        
        borrower = input("请输入借用人：").strip()
        borrow_date = input("请输入借用日期（YYYY-MM-DD，默认今天）：").strip()
        if not borrow_date:
            borrow_date = datetime.now().strftime("%Y-%m-%d")
        
        days_input = input("请输入预计借用天数（默认7天）：").strip()
        try:
            days = int(days_input) if days_input else 7
        except ValueError:
            days = 7
        
        expected_return = (datetime.strptime(borrow_date, "%Y-%m-%d") + timedelta(days=days)).strftime("%Y-%m-%d")
        purpose = input("请输入借用用途（可选）：").strip()
        remarks = input("请输入备注（可选）：").strip()
        
        if not all([record_id, borrower]):
            print("记录ID和借用人不能为空！")
            return
        
        borrow_record = BorrowRecord(record_id, equipment_id, borrower, borrow_date, expected_return, "", purpose, remarks)
        self.borrow_records[record_id] = borrow_record
        equipment.status = "借用中"
        
        print(f"设备 {equipment.name} 借用成功！预计归还日期：{expected_return}")
        self.save_data()
    
    def return_equipment(self):
        print("\n=== 设备归还 ===")
        record_id = input("请输入借用记录ID：").strip()
        
        if record_id not in self.borrow_records:
            print("借用记录ID不存在！")
            return
        
        record = self.borrow_records[record_id]
        if record.status == "已归还":
            print("该设备已经归还！")
            return
        
        equipment = self.equipments.get(record.equipment_id)
        if not equipment:
            print("关联的设备不存在！")
            return
        
        return_date = input("请输入归还日期（YYYY-MM-DD，默认今天）：").strip()
        if not return_date:
            return_date = datetime.now().strftime("%Y-%m-%d")
        
        remarks = input("请输入归还备注（可选）：").strip()
        
        record.actual_return = return_date
        record.status = "已归还"
        if remarks:
            record.remarks += f" | 归还备注：{remarks}"
        
        equipment.status = "可用"
        
        print(f"设备 {equipment.name} 归还成功！")
        
        try:
            expected_date = datetime.strptime(record.expected_return, "%Y-%m-%d")
            actual_date = datetime.strptime(return_date, "%Y-%m-%d")
            if actual_date > expected_date:
                overdue_days = (actual_date - expected_date).days
                print(f"注意：设备超期 {overdue_days} 天归还！")
        except:
            pass
        
        self.save_data()
    
    def list_all_borrow_records(self):
        print("\n=== 所有借用记录 ===")
        if not self.borrow_records:
            print("暂无借用记录。")
            return
        
        print(f"共有 {len(self.borrow_records)} 条借用记录：")
        for i, record in enumerate(self.borrow_records.values(), 1):
            equipment_name = self.equipments.get(record.equipment_id, {}).name if record.equipment_id in self.equipments else "未知"
            print(f"{i}. {record} | 设备：{equipment_name}")
    
    def search_borrow_records(self):
        print("\n=== 查询借用记录 ===")
        print("1. 按借用人查询")
        print("2. 按设备ID查询")
        print("3. 查询未归还记录")
        print("4. 查询超期记录")
        
        choice = input("请选择查询方式：").strip()
        
        if choice == '1':
            borrower = input("请输入借用人：").strip()
            results = [r for r in self.borrow_records.values() if borrower in r.borrower]
            self._display_borrow_results(results, f"借用人（{borrower}）")
        
        elif choice == '2':
            equipment_id = input("请输入设备ID：").strip()
            results = [r for r in self.borrow_records.values() if r.equipment_id == equipment_id]
            self._display_borrow_results(results, f"设备ID（{equipment_id}）")
        
        elif choice == '3':
            results = [r for r in self.borrow_records.values() if r.status == "借用中"]
            self._display_borrow_results(results, "未归还记录")
        
        elif choice == '4':
            today = datetime.now().strftime("%Y-%m-%d")
            overdue_records = []
            for record in self.borrow_records.values():
                if record.status == "借用中":
                    try:
                        if datetime.strptime(record.expected_return, "%Y-%m-%d") < datetime.strptime(today, "%Y-%m-%d"):
                            overdue_records.append(record)
                    except:
                        pass
            self._display_borrow_results(overdue_records, "超期记录")
        
        else:
            print("无效的选择！")
    
    def _display_borrow_results(self, results: List[BorrowRecord], search_type: str):
        if results:
            print(f"\n{search_type}查询结果（共{len(results)}条）：")
            for i, record in enumerate(results, 1):
                equipment_name = self.equipments.get(record.equipment_id, {}).name if record.equipment_id in self.equipments else "未知"
                print(f"{i}. 记录ID：{record.record_id} | 设备：{equipment_name} | 借用人：{record.borrower}")
                print(f"    借用日期：{record.borrow_date} | 预计归还：{record.expected_return} | 状态：{record.status}")
                if record.actual_return:
                    print(f"    实际归还：{record.actual_return}")
                if record.purpose:
                    print(f"    用途：{record.purpose}")
                print()
        else:
            print(f"未找到匹配的借用记录。")
    
    def show_statistics(self):
        print("\n=== 系统统计信息 ===")
        print(f"设备总数：{len(self.equipments)}")
        print(f"实验室总数：{len(self.laboratories)}")
        print(f"借用记录总数：{len(self.borrow_records)}")
        
        if self.equipments:
            print("\n设备状态统计：")
            status_count = {}
            category_count = {}
            total_value = 0
            
            for equipment in self.equipments.values():
                status_count[equipment.status] = status_count.get(equipment.status, 0) + 1
                category_count[equipment.category] = category_count.get(equipment.category, 0) + 1
                total_value += equipment.price
            
            for status, count in status_count.items():
                print(f"  {status}：{count} 台")
            
            print("\n设备类别统计：")
            for category, count in category_count.items():
                print(f"  {category}：{count} 台")
            
            print(f"\n设备总价值：￥{total_value:.2f}")
        
        if self.borrow_records:
            active_borrows = len([r for r in self.borrow_records.values() if r.status == "借用中"])
            returned_borrows = len([r for r in self.borrow_records.values() if r.status == "已归还"])
            
            print(f"\n借用状态统计：")
            print(f"  进行中：{active_borrows} 条")
            print(f"  已归还：{returned_borrows} 条")
            
            today = datetime.now().strftime("%Y-%m-%d")
            overdue_count = 0
            for record in self.borrow_records.values():
                if record.status == "借用中":
                    try:
                        if datetime.strptime(record.expected_return, "%Y-%m-%d") < datetime.strptime(today, "%Y-%m-%d"):
                            overdue_count += 1
                    except:
                        pass
            
            if overdue_count > 0:
                print(f"  超期未还：{overdue_count} 条")
    
    def export_lab_report(self):
        print("\n=== 导出实验室设备报告 ===")
        lab_id = input("请输入实验室ID：").strip()
        
        if lab_id not in self.laboratories:
            print("实验室ID不存在！")
            return
        
        laboratory = self.laboratories[lab_id]
        lab_equipments = [eq for eq in self.equipments.values() if eq.lab_id == lab_id]
        
        filename = f"lab_report_{lab_id}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.txt"
        
        try:
            with open(filename, 'w', encoding='utf-8') as f:
                f.write("=" * 60 + "\n")
                f.write(f"实验室设备报告\n")
                f.write("=" * 60 + "\n\n")
                
                f.write(f"实验室信息：\n")
                f.write(f"  实验室ID：{laboratory.lab_id}\n")
                f.write(f"  实验室名称：{laboratory.name}\n")
                f.write(f"  实验室位置：{laboratory.location}\n")
                f.write(f"  管理员：{laboratory.manager}\n")
                f.write(f"  容量：{laboratory.capacity}\n")
                f.write(f"  描述：{laboratory.description}\n\n")
                
                f.write(f"设备清单：\n")
                if lab_equipments:
                    total_value = 0
                    status_count = {}
                    
                    for i, equipment in enumerate(lab_equipments, 1):
                        f.write(f"  {i}. {equipment.name}\n")
                        f.write(f"     设备ID：{equipment.equipment_id}\n")
                        f.write(f"     类别：{equipment.category}\n")
                        f.write(f"     型号：{equipment.model}\n")
                        f.write(f"     状态：{equipment.status}\n")
                        f.write(f"     价格：￥{equipment.price}\n")
                        f.write(f"     购买日期：{equipment.purchase_date}\n\n")
                        
                        total_value += equipment.price
                        status_count[equipment.status] = status_count.get(equipment.status, 0) + 1
                    
                    f.write(f"设备统计：\n")
                    f.write(f"  设备总数：{len(lab_equipments)}\n")
                    f.write(f"  设备总价值：￥{total_value:.2f}\n")
                    f.write(f"  状态分布：\n")
                    for status, count in status_count.items():
                        f.write(f"    {status}：{count} 台\n")
                else:
                    f.write("  暂无设备\n")
                
                f.write(f"\n报告生成时间：{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
                f.write("=" * 60 + "\n")
            
            print(f"实验室设备报告已导出到文件：{filename}")
        
        except Exception as e:
            print(f"报告导出失败：{e}")
    
    def run(self):
        print("欢迎使用实验室设备管理系统！")
        
        while True:
            self.show_main_menu()
            choice = input("\n请选择功能：").strip()
            
            if choice == '1':
                self.equipment_management()
            elif choice == '2':
                self.laboratory_management()
            elif choice == '3':
                self.borrow_management()
            elif choice == '4':
                self.statistics_management()
            elif choice == '5':
                self.save_data()
            elif choice == '0':
                print("感谢使用实验室设备管理系统！再见！")
                self.save_data()
                break
            else:
                print("无效的选择，请重新输入！")
    
    def show_main_menu(self):
        print("\n" + "=" * 40)
        print("实验室设备管理系统 - 主菜单")
        print("=" * 40)
        print("1. 设备管理")
        print("2. 实验室管理")
        print("3. 借用管理")
        print("4. 统计查询")
        print("5. 保存数据")
        print("0. 退出系统")
        print("=" * 40)
    
    def equipment_management(self):
        while True:
            print("\n" + "-" * 30)
            print("设备管理")
            print("-" * 30)
            print("1. 添加设备")
            print("2. 删除设备")
            print("3. 修改设备")
            print("4. 查询设备")
            print("5. 显示所有设备")
            print("0. 返回主菜单")
            print("-" * 30)
            
            choice = input("请选择功能：").strip()
            
            if choice == '1':
                self.add_equipment()
            elif choice == '2':
                self.delete_equipment()
            elif choice == '3':
                self.update_equipment()
            elif choice == '4':
                self.search_equipment()
            elif choice == '5':
                self.list_all_equipments()
            elif choice == '0':
                break
            else:
                print("无效的选择，请重新输入！")
    
    def laboratory_management(self):
        while True:
            print("\n" + "-" * 30)
            print("实验室管理")
            print("-" * 30)
            print("1. 添加实验室")
            print("2. 删除实验室")
            print("3. 修改实验室")
            print("4. 显示所有实验室")
            print("0. 返回主菜单")
            print("-" * 30)
            
            choice = input("请选择功能：").strip()
            
            if choice == '1':
                self.add_laboratory()
            elif choice == '2':
                self.delete_laboratory()
            elif choice == '3':
                self.update_laboratory()
            elif choice == '4':
                self.list_all_laboratories()
            elif choice == '0':
                break
            else:
                print("无效的选择，请重新输入！")
    
    def borrow_management(self):
        while True:
            print("\n" + "-" * 30)
            print("借用管理")
            print("-" * 30)
            print("1. 设备借用")
            print("2. 设备归还")
            print("3. 显示所有借用记录")
            print("4. 查询借用记录")
            print("0. 返回主菜单")
            print("-" * 30)
            
            choice = input("请选择功能：").strip()
            
            if choice == '1':
                self.borrow_equipment()
            elif choice == '2':
                self.return_equipment()
            elif choice == '3':
                self.list_all_borrow_records()
            elif choice == '4':
                self.search_borrow_records()
            elif choice == '0':
                break
            else:
                print("无效的选择，请重新输入！")
    
    def statistics_management(self):
        while True:
            print("\n" + "-" * 30)
            print("统计查询")
            print("-" * 30)
            print("1. 系统统计信息")
            print("2. 导出实验室设备报告")
            print("0. 返回主菜单")
            print("-" * 30)
            
            choice = input("请选择功能：").strip()
            
            if choice == '1':
                self.show_statistics()
            elif choice == '2':
                self.export_lab_report()
            elif choice == '0':
                break
            else:
                print("无效的选择，请重新输入！")

def main():
    try:
        system = LabEquipmentSystem()
        system.run()
    except KeyboardInterrupt:
        print("\n\n程序被用户中断，正在保存数据...")
        try:
            system.save_data()
        except:
            pass
        print("数据保存完成，程序退出。")
    except Exception as e:
        print(f"程序运行出错：{e}")

if __name__ == "__main__":
    main()
